package cn.teduymdj.jxc.service.impl;

import cn.teduymdj.jxc.ex.ServiceException;
import cn.teduymdj.jxc.mapper.GoodsMapper;
import cn.teduymdj.jxc.mapper.SaleListGoodsMapper;
import cn.teduymdj.jxc.mapper.SaleListMapper;
import cn.teduymdj.jxc.pojo.dto.*;
import cn.teduymdj.jxc.pojo.entity.CustomerReturnList;
import cn.teduymdj.jxc.pojo.entity.SaleList;
import cn.teduymdj.jxc.pojo.entity.SaleListGoods;
import cn.teduymdj.jxc.pojo.vo.*;
import cn.teduymdj.jxc.service.SaleListGoodsService;
import cn.teduymdj.jxc.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import static cn.teduymdj.jxc.service.impl.CustomerReturnListGoodsServiceImpl.PAID_STATE;

/**
 * 销售业务实现
 * 欧阳林枫
 */
@Slf4j
@Service
@Transactional
public class SaleListGoodsServiceImpl implements SaleListGoodsService {
    @Autowired
    SaleListMapper saleListMapper;

    @Autowired
    SaleListGoodsMapper saleListGoodsMapper;

    @Autowired
    GoodsMapper goodsMapper;

    @Override
    public void save(SaleListAddNewDTO02 saleListAddNewDTO02) {
        log.debug("处理保存销售商品的业务:{}", saleListAddNewDTO02);
        if (saleListAddNewDTO02.getSaleNumber()==null) {
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST, "保存失败,单号不存在");
        }
        int saleNumber = saleListMapper.countBySaleNumber(saleListAddNewDTO02.getSaleNumber());
        if (saleNumber != 0) {
            // 是:添加失败，抛出异常，单号已存在
            String message = "保存销售商品失败，单号已存在!";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        SaleListAddNewDTO saleListAddNewDTO = new SaleListAddNewDTO();
        BeanUtils.copyProperties(saleListAddNewDTO02,saleListAddNewDTO);
        int result = saleListMapper.insert(saleListAddNewDTO);
        // 判断是否添加成功
        if (result != 1) {
            String message = "添加失败，服务器忙，请稍后重试";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        List<SaleListGoodsAddNewDTO> saleListGoodsAddNewDTOList = saleListAddNewDTO02.getTableData();
        if (saleListGoodsAddNewDTOList==null){
            String message = "保存销售单据失败，销售单必须包含商品！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST, message);
        }
        // 保存销售商品信息
        for (SaleListGoodsAddNewDTO saleListGoodsAddNewDTO : saleListGoodsAddNewDTOList) {
            //判断单价乘数量和总金额是否相等
            BigDecimal price = saleListGoodsAddNewDTO.getPrice();
            Integer num = saleListGoodsAddNewDTO.getNum();
            BigDecimal number = new BigDecimal(num);
            BigDecimal total = saleListGoodsAddNewDTO.getTotal();
            if (price.multiply(number).equals(total)) {
                throw new ServiceException(ServiceCode.ERR_INSERT, "保存销售单信息失败,插入金额有误!");
            }
            //通过id查询数据库信息是否存在
            Long goodsId = saleListGoodsAddNewDTO.getGoodsId();
            GoodsStandardVO goods = goodsMapper.getStandardById(goodsId);
            if (goods==null){
                throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"保存销售单信息失败,商品不存在!");
            }
            //设置销售单id
            Long id = saleListAddNewDTO.getId();
            saleListGoodsAddNewDTO.setSaleListId(id);
            //
            // 修改商品上一次进货价，进货均价，库存，状态
            goods.setLastPurchasingPrice(saleListGoodsAddNewDTO.getPrice());
            goods.setInventoryQuantity(goods.getInventoryQuantity());
            int t = 2;
            BigDecimal two = new BigDecimal(t);
            goods.setPurchasingPrice(goods.getLastPurchasingPrice().multiply(saleListGoodsAddNewDTO.getPrice()).divide(two));
            goods.setState(2);
            GoodsAddNewDTO goodsAddNewDTO = new GoodsAddNewDTO();
            BeanUtils.copyProperties(goods,goodsAddNewDTO);
            goodsMapper.addNew(goodsAddNewDTO);
        }

    }

    @Override
    public List<SaleListListItemVO> getSalelist(String saleNumber, String customerId, String state, String sTime, String eTime) {
        return saleListMapper.list();
    }

    @Override
    public List<SaleListGoodsListItemVO> getSaleListGoodsBySaleListId(Long saleListId) {
        return saleListGoodsMapper.listByListId(saleListId);
    }

    @Override
    public void delete(Long saleListId) {
        SaleListStandardVO queryResult = saleListMapper.getStandardById(saleListId);
        // 判断查询结果是否为null
        if (queryResult == null) {
            // 是：无此id对应的数据，将不允许执行删除操作，则抛出异常
            String message = "删除进货单失败，尝试访问的数据不存在！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        int rows = saleListMapper.deleteById(saleListId);
        if (rows != 1) {
            String message = "删除进货单失败，服务器忙，请稍后再尝试！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
        rows = saleListGoodsMapper.deleteByListId(saleListId);
        if (rows < 1) {
            String message = "删除进货单失败，服务器忙，请稍后再尝试！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
    }

    @Override
    public SaleList getSaleList(Long saleListId) {
        return null;
    }

    @Override
    public Integer getSaleTotalByGoodsId(Long goodsId) {
        return null;
    }

    @Override
    public void updateState(Integer state, Long id) {

    }

    @Override
    public List<SaleListGoods> getSaleListGoodsBySaleListId(Long saleListId, Long goodsTypeId, String codeOrName) {
        return null;
    }

    @Override
    public List<Object> getSaleDataByDay(String sTime, String eTime) {

        return null;
    }

    @Override
    public List<Object> getSaleDataByMonth(String sTime, String eTime) {
        return null;
    }

    @Override
    public void setPaid(Long id) {
        updateEnableById(id, 1);
    }

    @Override
    public void setUnpaid(Long id) {
        updateEnableById(id, 2);
    }

    @Override
    public List<SaleListCountListItemVO> getSaleListGoodsByCondition(SelectReturnCondition selectReturnCondition) {
        List<SaleListCountListItemVO> list = saleListGoodsMapper.listByCondition(selectReturnCondition);
        list.forEach(g->g.setType("销售"));
        return list;
    }

    private void updateEnableById(Long id, int isPaid) {

        SaleListStandardVO queryResult = saleListMapper.getStandardById(id);
        // 判断查询结果是否为null
        if (queryResult == null) {
            // 是：此id对应的数据不存在，则抛出异常(ERR_NOT_FOUND)
            String message = "修改支付状态失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 判断状态是否冲突（当前已经是目标状态）
        if (queryResult.getState().equals(isPaid)) {
            String message = "修改支付失败，退货单已经处于该状态！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        SaleListAddNewDTO saleListAddNewDTO = new SaleListAddNewDTO();
        saleListAddNewDTO.setId(id);
        saleListAddNewDTO.setState(isPaid);
        int rows = saleListMapper.update(saleListAddNewDTO);
        if (rows != 1) {
            String message = "修改支付失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

}
